import { useEffect, useState } from "react"
import { useSelector, useDispatch } from "react-redux"
import PropTypes from "prop-types"
import { Button, Modal, Spin } from "antd"
import { loadJS } from "../../../utils/loadJS"
import {
  loadPreviewDepsAction,
  loadJQueryAction
} from "../../../store/actions/flowableAction"


const baseUrl = import.meta.env.VITE_FLOWABLE_URL

const ProcessPreviewModal = ({
  processDefinitionId,
  isFinish,
  children
}) => {

  const previewDepsLoaded = useSelector(state => state.flowable.previewDepsLoaded)
  const jQueryLoaded = useSelector(state => state.flowable.jQueryLoaded)
  const dispatch = useDispatch()

  const [visible, setVisible] = useState(false)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (!window.FLOWABLE) {
      window.FLOWABLE = {
        APP_URL: {}
      }
    } else {
      if (!window.FLOWABLE.APP_URL) {
        window.FLOWABLE.APP_URL = {}
      }
    }

    window.FLOWABLE.APP_URL.getProcessInstanceModelJsonUrl = function (processDefinitionId) {
      return `/flowable-ui/app/rest/process-instances/${processDefinitionId}/model-json`;
    }
    window.FLOWABLE.APP_URL.getProcessInstanceModelJsonHistoryUrl = function (processDefinitionId) {
      return `/flowable-ui/app/rest/process-instances/history/${processDefinitionId}/model-json`;
    }
  }, [])

  const toggleVisible = () => {
    setVisible((visible) => !visible)
  }

  useEffect(() => {
    if (visible) {
      doLoadFlowableFiles()
    }
  }, [visible])

  const doLoadFlowableFiles = async () => {
    try {
      setLoading(true)
      if (!jQueryLoaded) {
        await dispatch(loadJQueryAction())
      }
      if (!previewDepsLoaded) { // 防止依赖文件重复加载，重复插入script标签
        await dispatch(loadPreviewDepsAction())
      }
      setTimeout(async () => {
        await loadJS(baseUrl + 'modeler/display/displaymodel.js', '#J_script_box')
        setLoading(false)
      }, 500)
    } catch (error) {
      setLoading(false)
    }
  }

  return <>
    <div onClick={toggleVisible}>
      {
        children ||
        <Button type="primary">显示流程图</Button>
      }
    </div>
    <Modal
      width={960}
      title="显示流程图"
      visible={visible}
      onCancel={toggleVisible}
      keyboard={false}
      maskClosable={false}
      footer={null}
      destroyOnClose
      centered
    >
      <Spin spinning={loading}>
        <div style={{
          minHeight: '60vh',
          maxHeight: '80vh',
          overflow: 'auto'
        }}>
          {
            isFinish ?
              <div
                id="bpmnModel"
                data-history-id={processDefinitionId}
                data-model-type="runtime"
              ></div> :
              <div
                id="bpmnModel"
                data-model-id={processDefinitionId}
                data-model-type="runtime"
              ></div>
          }
          <div id="J_script_box"></div>
        </div>
      </Spin>
    </Modal>
  </>
}

ProcessPreviewModal.propTypes = {
  processDefinitionId: PropTypes.string,
  isFinish: PropTypes.bool,
  children: PropTypes.node
}

export default ProcessPreviewModal